import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import javax.imageio.ImageIO;


public class ArtPiece {
	//Where images are stored, so they only have to be downloaded once
	public static final String IMAGE_STORAGE = "images/";
	//The size of each stored image
	public static final int STORED_SIZE = 200;
	
	public String author;
	public ArrayList<String> sampleUrls;
	public String title;
	
	public ArrayList<BufferedImage> getSampleImages()
	{
		ArrayList<BufferedImage> result = new ArrayList<BufferedImage>();
		for (String url : sampleUrls)
		{
			result.add(getImage(url));
		}
		return result;
	}
	
	public static BufferedImage getImage(String url)
	{
		System.out.println(url);
		String filePath = url.replace(":", "_");
		filePath = filePath.replace("/", "_");
		filePath = IMAGE_STORAGE + filePath;
		File file = new File(filePath);
		BufferedImage image;
		try {
			if (file.exists())
			{
			
				image = ImageIO.read(file);
			}
			else
			{
				File storage = new File(IMAGE_STORAGE);
				if (!storage.exists())
				{
					storage.mkdir();
				}
				URL link = new URL(url);
				image = ImageIO.read(link);
				if (image == null)
				{
					System.out.println("Image not found.  Skipping.");
				}
				else
				{
					Image scaled = image.getScaledInstance(STORED_SIZE, STORED_SIZE, BufferedImage.SCALE_DEFAULT);
					image = new BufferedImage(STORED_SIZE, STORED_SIZE, BufferedImage.TYPE_INT_RGB);
					image.getGraphics().drawImage(scaled, 0, 0, null);
					String fileType = url.substring(url.length() - 3);;
					ImageIO.write(image, fileType, file);
				}
			}
		} catch (IOException e) {
			image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
			e.printStackTrace();
		}
		return image;
	}
}
